<template>
  <div class="allocation-dialog-view">

    <el-dialog
        v-model="dialogShow"
        :close-on-click-modal="false"
        title="分配任务"
        width="900px"
        @closed="close"
    >

      <el-form
          ref="refForm"
          :model="formData"
          :rules="rule"
          class="demo-ruleForm"
          label-width="120px"
      >
        <el-form-item label="招商产品信息">
          <template v-if="datas.planInfo">
            <span>{{ getProductName(datas.planInfo) }}</span>
          </template>

        </el-form-item>

        <el-form-item v-if="datas.planInfo.planType == 2" label="规划招商地区">
          <span>{{
              datas.planDetail?.areaName ? datas.planDetail?.cityName + "/" + datas.planDetail?.areaName : datas.planDetail?.cityName ? datas.planDetail?.cityName : datas.planDetail?.provinceName
            }}</span>
        </el-form-item>

        <el-form-item v-if="datas.planInfo.planType == 1" label="招商终端">
          <span>{{ datas.planDetail?.terminalName }}</span>
        </el-form-item>

        <el-form-item v-if="datas.planInfo.planType == 1" label="终端所在地区">
          <span>{{ datas.planDetail?.terProvinceName }}/{{
              datas.planDetail?.terCityName
            }}/{{ datas.planDetail?.terAreaName }}</span>
        </el-form-item>

        <el-form-item label="跟进职员" prop="headId">
          <el-select
              v-model="formData.headId"
              placeholder="请选择职员"
              style="width: 100%"
              @change="headChange"
          >
            <el-option
                v-for="item in headOptions"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <div style="display: flex;justify-content: space-between;margin-bottom: 10px">
          <div>
            <el-button class="main-btn" size="small" type="primary" @click="onAgent">检索代理库</el-button>
            <el-button class="main-btn" size="small" type="primary" @click="onAdd">添加跟进代理</el-button>
            <el-button class="main-btn" size="small" type="primary" @click="onDate">设置相同开发跟进期限</el-button>
          </div>

          <div>
            <span>未找到代理商</span>
            <el-button style="margin: 0 10px" type="text" @click="onCreate">创建代理商</el-button>
          </div>

        </div>

        <el-table :data="tableData" border size="medium">
          <el-table-column type="index"/>
          <el-table-column
              :show-overflow-tooltip="true"
              align="left"
              header-align="center"
              label="代理名称"
              prop="agentName"
          >
            <template #default="scope">
              <el-autocomplete
                  v-if="!scope.row.agentId"
                  v-model="scope.row.agentName"
                  :fetch-suggestions="querySearchAsyncAgent"
                  placeholder="请输入代理商名称"
                  style="width: 100%"
                  @select="(val) => {handleSelectAgent(val,scope.$index)}"
              >
                <template #default="{ item }">
                  <div v-if="item.agentType == 'agent'" class="distributeName">{{ item.agentName }}</div>
                  <div v-else class="distributeName">{{ item.userName }}</div>
                </template>
              </el-autocomplete>

              <span v-else>{{ scope.row.agentName }}</span>
            </template>
          </el-table-column>
          <el-table-column
              :show-overflow-tooltip="true"
              align="left"
              header-align="center"
              label="所在地区"
          >
            <template #default="{row}">
              <span v-if="row.id && row.agentType == 'agent'">{{ row.provinceName }}/{{ row.cityName }}/{{
                  row.areaName
                }}</span>
              <span v-else-if="row.id">{{ row.address }}</span>
            </template>
          </el-table-column>
          <el-table-column
              :show-overflow-tooltip="true"
              align="center"
              header-align="center"
              label="代理商状态"
          >
            <template #default="{row}">
              <!--                            <span v-if="row.agentId && row.tradeStatus == 1">正式代理商</span>-->
              <!--                            <span v-else-if="row.agentId">准代理商</span>-->
              {{ getLabel('agent_status', row.agentStatus) }}
            </template>
          </el-table-column>
          <el-table-column
              :show-overflow-tooltip="true"
              align="left"
              header-align="center"
              label="开发跟进期限"
          >
            <template #default="{row}">
              <date-picker
                  v-if="row.isEdit"
                  v-model:date="row.dealTime"
                  :disabled-date="disabledDate"
                  placeholder="请选择跟进开发期限"
                  style="width: 100%"
              />
              <span v-else-if="row.dealTime">{{ dateFormat('yyyy-mm-dd', row.dealTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
              align="left"
              header-align="center"
              label="操作"
              width="130px"
          >
            <template #default="scope">
              <el-button v-if="!scope.row.isEdit" type="text" @click="onEdit(scope.row)">编辑</el-button>
              <el-button v-else type="text" @click="onEnd(scope.row)">完成</el-button>
              <el-button type="text" @click="onRemove(scope.$index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
              class="border-btn"
              size="small"
              @click="close"
          >取消
          </el-button>
          <el-button
              class="main-btn"
              size="small"
              type="primary"
              @click="confirm"
          >确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
        v-model="dateShow"
        :close-on-click-modal="false"
        width="400px"
        @closed="dateClose"
    >

      <el-form ref="dateForm" :model="formData" :rules="rule">
        <el-form-item label="开发跟进期限" prop="dealTime">
          <date-picker
              v-model:date="formData.dealTime"
              :disabled-date="disabledDate"
              placeholder="请选择跟进开发期限"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
              class="border-btn"
              size="small"
              @click="dateClose"
          >取消
          </el-button>
          <el-button
              class="main-btn"
              size="small"
              type="primary"
              @click="dateConfirm"
          >确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <fromDialog ref="fromDialog"/>

    <detail-drawer
        ref="detailDrawer"
        :size-width="1000"
        custom-title
    >
      <template #title>
        <div style="display: flex;justify-content: space-between">
          <span>检索代理库</span>

          <el-button class="main-btn" size="small" type="primary" @click="agentConfirm">确定</el-button>
        </div>

      </template>
      <template #contents>

        <agentLibrary ref="agentLibrary" :datas="libraryData" :list="tableData" is-select/>

      </template>
    </detail-drawer>

  </div>

</template>

<script>
import {crmStore} from "../../../../../store";
import {useRouter} from 'vue-router'
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, toRefs} from 'vue'

export default defineComponent({
  name: 'AllocationDialog',
  emits: ['success'],
  components: {
    agentLibrary: defineAsyncComponent(
        () => import('../../detail/modules/agentLibrary.vue')
    ),
    fromDialog: defineAsyncComponent(
        () => import('../../../customer/modules/fromDialog.vue')
    )
  },
  setup(props, {emit}) {
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const rule = {
      agentName: [
        {required: true, message: '请选择代理商', trigger: 'blur'}
      ],
      headId: [
        {required: true, message: '请选择职员', trigger: 'blur'}
      ],
      dealTime: [
        {
          type: 'date',
          required: true,
          message: '请选择跟进开发期限',
          trigger: 'change',
        },
      ],
    }
    var data = reactive({
      dialogShow: false,
      dateShow: false,
      tableData: [],
      formData: {
        planDetailId: 0, // 规划明细id
        headId: '', // 跟进职员id
        headName: '', // 跟进职员名称
        productId: 0, // 产品id
      },
      headOptions: crmStore.getters['company/getHeadOptions'],
      agents: [],
      datas: {},
      refForm: null,
      isNot: false,
      dateForm: null,
      libraryData: {},
      detailDrawer: null,
      agentLibrary: null,
      fromDialog: null,
    })

    const onCreate = () => {
      data.fromDialog.open()
    }

    const onAdd = () => {
      data.tableData.push({isEdit: true})
    }

    const onRemove = (index) => {
      data.tableData.splice(index, 1)
    }

    const onEdit = (row) => {
      row.isEdit = true
    }

    const onEnd = (row) => {
      row.isEdit = false
    }

    const dateConfirm = () => {
      data.dateForm.validate((val) => {
        if (val) {
          data.tableData.forEach(item => {
            item.dealTime = data.formData.dealTime
          })
          dateClose()
        }
      })

    }

    const dateClose = () => {
      data.formData.dealTime = ''
      data.dateForm.clearValidate()
      data.dateShow = false
    }

    const onDate = () => {
      if (!data.tableData.length) {
        currentInstance.proxy.customMessage({type: 'error', message: '请添加代理商'})
        return;
      }
      data.dateShow = true
    }

    const onAgent = () => {
      data.detailDrawer.open()
    }

    const agentConfirm = () => {
      if (!data.agentLibrary.selects.length) {
        currentInstance.proxy.customMessage({type: 'error', message: '请选择代理商'})
        return
      }
      data.agentLibrary.selects.forEach(a => {
        let item = {...a}
        item.agentId = item.id
        item.dealTime = ''
        item.isEdit = false
        if (!item.agentName) {
          item.agentName = item.userName
        }
        data.tableData.push(item)
      })
      data.detailDrawer.close()
    }

    const getAgent = () => {
      const params = {
        startTime: null,
        endTime: null,
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        tradeStatus: '',
        from: '1',
        pageSize: 100,
        page: 1,
        agentType: data.formData.radio
      }
      api.channelAgent.POTENTIALAGENT_LIST(params).then((res) => {
        if (res.code === 0) {
          data.agents = res.data.list || []
        }
      })
    }

    const open = (item) => {
      data.datas = item
      data.formData.planDetailId = item.planDetail.id
      data.formData.productId = item.planDetail.productId
      data.dialogShow = true

      data.libraryData.productId = item.planDetail.productId
      if (item.planDetail.planType == 1) {
        data.libraryData.from = '2'
        data.libraryData.provinceCode = item.planDetail.terminalProvince
        data.libraryData.cityCode = item.planDetail.terminalCity
        data.libraryData.areaCode = item.planDetail.terminalArea
        data.libraryData.terminalId = item.planDetail.terminalId
      } else {
        data.libraryData.from = '1'
        data.libraryData.provinceCode = item.planDetail.provinceCode
        data.libraryData.cityCode = item.planDetail.cityCode
        data.libraryData.areaCode = item.planDetail.areaCode
      }
    }

    const confirm = () => {
      data.refForm.validate((value) => {
        if (value) {
          if (!data.tableData.length) {
            currentInstance.proxy.customMessage({type: 'error', message: '请添加代理商'})
            return
          }
          for (let i = 0; i < data.tableData.length; i++) {
            if (!data.tableData[i].id) {
              currentInstance.proxy.customMessage({type: 'error', message: '请选择代理商'})
              return;
            }
            if (!data.tableData[i].dealTime) {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: '请选择' + data.tableData[i].agentName + '开发跟进期限'
              })
              return;
            }
          }
          const a = {...data.formData}
          a.planDetailId = Number(a.planDetailId)
          a.productId = Number(a.productId)
          a.headId = Number(a.headId)
          a.allocationAgentInfo = data.tableData

          api.plan.ALLOCATION_AGENT_CREATE(a).then(res => {
            if (!res.code) {
              currentInstance.proxy.customMessage({type: 'success', message: '分配成功'})
              emit('success')
              close()
            } else {
              currentInstance.proxy.customMessage({type: 'error', message: res.msg})
            }
          })
        }
      })
    }

    const close = () => {
      data.formData = {
        planDetailId: 0, // 规划明细id
        agentId: '', // 分配的代理商id
        agentName: '',
        headId: '', // 跟进职员id
        headName: '', // 跟进职员名称
        dealTime: '', // 分配的跟进开发期限
        productId: 0, // 产品id
        radio: 'agent'
      }
      data.tableData = []
      data.isNot = false
      data.dialogShow = false
    }

    // 获取代理商列表
    const querySearchAsyncAgent = async (queryString, cb) => {
      const a = {
        agentType: '',
        keyWord: queryString,
      }
      let results = []
      const res = await api.editorial.EDITORIAL_KEYWORDS(a)
      if (!res.code && res.data) {
        results = res.data.list || []
        if ((!res.data.list || !res.data.list.length) && queryString) {
          data.isNot = true
        } else {
          data.isNot = false
        }
      }
      cb(results)
    }

    // 代理商事件
    const handleSelectAgent = (val, index) => {
      let x = data.tableData.findIndex(a => a.id == val.id)
      if (x != -1) {
        currentInstance.proxy.customMessage({type: 'error', message: '代理商已添加'})
        return
      }
      let a = {...val}
      a.agentId = a.id
      a.dealTime = data.tableData[index].dealTime
      a.isEdit = data.tableData[index].isEdit
      if (!a.agentName) {
        a.agentName = a.userName
      }
      data.tableData[index] = a
    }

    const headChange = (val) => {
      const index = data.headOptions.findIndex(a => a.id == val)
      if (index != -1) {
        data.formData.headName = data.headOptions[index].realName
      }
    }

    const disabledDate = (time) => {
      return !(time.getTime() > Date.now())
    }

    onMounted(() => {
      getAgent()
    })

    return {
      ...toRefs(data),
      rule,

      confirm,
      close,
      open,
      disabledDate,
      headChange,
      querySearchAsyncAgent,
      handleSelectAgent,
      onCreate,
      onAdd,
      onEdit,
      onEnd,
      dateConfirm,
      dateClose,
      onDate,
      onAgent,
      agentConfirm,
      onRemove,
    }
  }
})
</script>

<style scoped>

</style>
